//获取应用实例
const app = getApp()
let ServiceUrl = app.globalData.ServiceUrl;
//console.log(datas);
Page({
  data: {
    activeNames: ['1'],
    role_state:'',
    company_name: '',
    company_logo: '',
    orderAll: 0,
    orderMonth: 0,
    assistanceAll:'',//老汤查看助医服务全部订单量
    assistanceMonth:'',//老汤查看助医服务本月订单量
    accompanyAll:'',//老汤查看就医服务全部订单量
    accompanyMonth:'',//老汤查看就医服务本月订单量
    userInfo: {},
    user_name:'',
    hasUserInfo: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    
    
    user_id:'',
    state:0,//改变其值决定返回状态是否刷新
    avatar_url:'',
    active: 1,
    checked: '',
    logout: false
  },
  
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
      //传递的user_id
    console.log(options);
    this.setData({user_id:options.user_id})
    let that = this;
    //如果无缓存信息，则展示登录按钮
    if(wx.getStorageSync('uid') && wx.getStorageSync('userName') && wx.getStorageSync('avatarUrl')){
      var is_logout = true;  //如果存在，则让logout为假
      console.log('存在用户信息')
    }else{
      var is_logout = false;  //如果不存在，则让logout为真
      console.log('不存在用户信息')
    }
    if(!options.user_id && wx.getStorageSync('uid')){
      console.log('存在user_id')
      this.setData({
        hasUserInfo: false,
        user_id: wx.getStorageSync('uid'),
        role_state: wx.getStorageSync('roleState'),
        logout: is_logout,
        avatar_url: wx.getStorageSync('avatarUrl'),
        user_name: wx.getStorageSync('userName'),
        role_state: wx.getStorageSync('roleState'),
        checked: wx.getStorageSync('checked')
      })
      if(wx.getStorageSync('roleState') == 1){
        that.setData({
          assistanceAll: wx.getStorageSync('assistanceAll'),
          assistanceMonth: wx.getStorageSync('assistanceMonth'),
          accompanyAll: wx.getStorageSync('accompanyAll'),
          accompanyMonth: wx.getStorageSync('accompanyMonth')
        })
      }else{
        that.setData({
          orderAll: wx.getStorageSync('orderAll'),
          orderMonth: wx.getStorageSync('orderMonth')
        })
      }
    }else{
      console.log('不存在user_id')
    }
    if(options =='' || options.user_id=='' || options.user_id == 'undefined'){
      console.log('此时传值为空')
      that.setData({
        user_id: wx.getStorageSync('uid'),
        role_state: wx.getStorageSync('roleState'),
        logout: is_logout,
        avatarUrl: wx.getStorageSync('avatarUrl'),
        userName: wx.getStorageSync('userName'),
        role_state: wx.getStorageSync('roleState'),
        checked: wx.getStorageSync('checked')
      })
    }else{
      that.getUserData(that.data.user_id);
    }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    wx.hideLoading();
  },
  //向后台发送请求获取信息
  getUserData: function(user_id){
    let that = this
      //获取此用户应有的信息（公司名、LOGO、个人姓名、应管辖的订单量、最新订单等）
     wx.request({
      url: ServiceUrl + 'getPageInfo',
       data:{user_id: user_id},
      success:function(res){
        console.log(res);
        if(res.data.state == 200){//如果res.data中无数据，则不执行
            //存储用户user_id
            wx.setStorageSync('uid', res.data.data.user_id);
            wx.setStorageSync('roleState', res.data.data.role_state);
            wx.setStorageSync('companyLogo', res.data.data.company_logo);
            wx.setStorageSync('companyName', res.data.data.company_name);
            wx.setStorageSync('userName', res.data.data.user_name);
            wx.setStorageSync('logout', true);
            wx.setStorageSync('avatarUrl', res.data.data.avatar_url);
            wx.setStorageSync('userName', res.data.data.user_name);
            wx.setStorageSync('roleState', res.data.data.role_state);
            //转化"true"和"false"，带双引号的为字符串，系统不认     
            if(res.data.data.is_take_order == 'false'){
              wx.setStorageSync('checked', false);
            }else{
              wx.setStorageSync('checked', true);
            }
            if(res.data.data.is_take_order == 'false'){
              var CK = false;
            }else{
              var CK = true;
            }
            if(res.data.data.role_state == 1){
              that.setData({
                assistanceAll: res.data.data.assistanceAll,
                assistanceMonth: res.data.data.assistanceMonth,
                accompanyAll: res.data.data.accompanyAll,
                accompanyMonth: res.data.data.accompanyMonth,
              })
              //老汤要看到的数据
              wx.setStorageSync('assistanceAll', res.data.data.assistanceAll);
              wx.setStorageSync('assistanceMonth', res.data.data.assistanceMonth);
              wx.setStorageSync('accompanyAll', res.data.data.accompanyAll);
              wx.setStorageSync('accompanyMonth', res.data.data.accompanyMonth);
            }else{
              that.setData({
                orderAll: res.data.data.orderAll,
                orderMonth: res.data.data.orderMonth,
              })
              wx.setStorageSync('orderAll', res.data.data.orderAll);
              wx.setStorageSync('orderMonth', res.data.data.orderMonth);
            }
            that.setData({
              company_logo: res.data.data.company_logo,
              company_name: res.data.data.company_name,
              user_name: res.data.data.user_name,
              role_state: res.data.data.role_state,
              user_id:res.data.data.user_id,
              avatar_url: res.data.data.avatar_url,
              checked:CK,
              logout: true
            });
          }else if(res.data.state==400){
            that.remove();
          }
      },
      fail:function(res){
        wx.showModal({
          title:"提示",
          content:"发送请求失败",
          showCancel: false,
          confirmColor: 'skyblue',
        })
      }
    });
  },
   /**
   * onTabbarChange tabbar功能
   * @param {*} event 
   */
  onTabbarChange(event) {
    this.setData({ active: event.detail });
    //console.log(event.detail)
    let user_id = this.data.user_id;
    if(event.detail == 1){
      wx.redirectTo({
        url: '../index/index?user_id=' + user_id,
      })
    }else if(event.detail == 0){
      wx.redirectTo({
        url: '../index/home?user_id=' + user_id,
      })
    }
  },
  /**
   * 我要接单开关
   * @param {*} param0 
   */
  onSwitchChange({ detail }) {
    let that = this;
    console.log(detail)
    let user_id = that.data.user_id;
    if(user_id != ''){
      if(detail == false){
        wx.showModal({
          title: '提示',
          content: '是否关闭接单？',
          confirmColor: 'skyblue',
          success: (res) => {
            if (res.confirm) {
              wx.request({
                url: ServiceUrl + 'isTakeOrder',
                data: {
                  is_take_order: false,
                  user_id: that.data.user_id
                },
                success: function(res){
                  console.log(res)
                  that.setData({checked:detail});
                  wx.removeStorageSync('checked');
                  wx.setStorageSync('checked', false)
                }
              })
              wx.showToast({
                title: '已停止接单功能',
                icon: 'none'
              })
            }
          },
        });
      }else{
        wx.showModal({
          title: '提示',
          content: '是否开启接单？',
          confirmColor: 'skyblue',
          success: (res) => {
            if (res.confirm) {
              
        wx.request({
          url: ServiceUrl + 'isTakeOrder',
          data: {
            is_take_order: true,
            uid: that.data.user_id
          },
          success: function(res){
            console.log(res)
            that.setData({checked:detail});
            wx.removeStorageSync('checked');
            wx.setStorageSync('checked', true)
          }
        })
        wx.showToast({
          title: '已开启接单功能',
          icon: 'none'
        })
            }
          },
        });
      }
    }else{
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },
  //上拉加载
  onReachBottom:function (){
    this.getUserData(this.data.user_id)
  },
 
  onPullDownRefresh: function (options) {
    let that = this;
    that.getUserData(that.data.user_id);
  },
  //获取用户信息
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  rewardOrder:function(){
    let user_id = this.data.user_id;
    if(user_id != ''){
      wx.navigateTo({
        url: '../index/reward?user_id=' + user_id
      })
    }
  },
  accompanyOrder:function(){
    let user_id = this.data.user_id;
    let role_state = this.data.role_state;
    console.log(user_id)
    if(user_id != ''){
      wx.navigateTo({
        url: '../search/accompany?user_id=' + user_id + '&active=a' + '&role_state=' + role_state
      })
    }else{
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },
  //助医服务订单
  assistanceOrder:function(){
    let user_id = this.data.user_id;
    let role_state = this.data.role_state;
    console.log(user_id)
    if(user_id != ''){
      wx.navigateTo({
        url: '../search/assistance?user_id=' + user_id + '&active=a' + '&role_state=' + role_state
      })
    }else{
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
    }
  },
    //订阅通知
    subscriptions:function(){
      let user_id = wx.getStorageSync('uid');
      let role_state = this.data.role_state;
      if(user_id != ''){
        wx.navigateTo({
          url: '../index/subscriptions?user_id=' + user_id + '&role_state=' + role_state
        })
      }else{
        console.log(uid)
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
    },
    //登录按钮
    goLogin:function(){
      wx.redirectTo({
        url: '../login/index',
      })
    },
    //清除缓存
    remove:function(){
      let that = this
      if(that.data.role_state == 1){
        wx.removeStorageSync('assistanceAll'),
        wx.removeStorageSync('assistanceMonth');
        wx.removeStorageSync('accompanyAll'),
        wx.removeStorageSync('accompanyMonth');
      }else{
        wx.removeStorageSync('orderAll');
        wx.removeStorageSync('orderMonth');
      }
      wx.removeStorageSync('companyLogo');
      wx.removeStorageSync('companyName');
      wx.removeStorageSync('userName');
      wx.removeStorageSync('avatarUrl');
      wx.removeStorageSync('roleState');
      wx.removeStorageSync('uid');
      wx.removeStorageSync('logout');
      wx.setStorageSync('logout', false);
      that.setData({
        company_logo:'https://wx.xiangban365.com/images/logo.png',
        company_name:'游客模式',
        user_name:'',
        avatar_url:'',
        role_state: '',
        user_id:'',
        orderAll: 0,//已完成订单
        orderMonth: 0,//待通过订单
        logout: false
      });
    },
    /**
     * 退出登录
     */
    logout: function(){
      let that = this;
      wx.showModal({
        title: '提示',
        content:'是否要退出登录？',
        confirmColor: 'skyblue',
        success: (res) =>{
          if(res.confirm){
            that.remove();
            console.log(that.data.logout)
            //缓冲
            wx.showLoading({
              title: '注销',
            });
            setTimeout(function () {
              wx.hideLoading()
              //刷新页面
              wx.redirectTo({
                url: './../index/index',
                success: (res) => {},
                fail: (res) => {},
                complete: (res) => {},
              })
            }, 1200);
          } else if(res.cancel){
            console.log('否')
          }
        }
      })
    }
})
